package studio.xiaoyun.web.restController;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import studio.xiaoyun.common.tool.FileTool;
import studio.xiaoyun.core.Config;
import studio.xiaoyun.core.exception.CoreException;
import studio.xiaoyun.core.exception.ErrorCode;
import studio.xiaoyun.web.RestResult;
import studio.xiaoyun.web.resource.UploadFileResource;

import java.io.File;
import java.util.*;

/**
 * 文件上传、下载
 * @author  岳正灵
 */
@RestController
@RequestMapping("/v1/file")
public class FileRestController {
    private Logger log = LoggerFactory.getLogger(FileRestController.class);

    /**
     * 上传文件
     * @param file 上传的文件
     * @return 文件相关信息
     */
    @RequestMapping(value="/upload",method = RequestMethod.POST)
    public RestResult uploadFile(MultipartFile file){
        String extension = FileTool.getFileExtension(file.getOriginalFilename());
        if(!Config.isAllowedExtensions(extension)){
            throw new CoreException(ErrorCode.PARAMETER_ERROR,"不支持的文件类型");
        }
        String newFileName = Config.getUploadPath()+UUID.randomUUID().toString();
        if(extension.length()>0){
            newFileName += "."+extension;
        }
        File newFile  = new File(newFileName);
        try {
            file.transferTo(newFile);
        }catch(Exception e){
            log.error("上传文件失败!",e);
            throw new CoreException(ErrorCode.INTERNAL_SERVER_ERROR,"上传失败");
        }
        UploadFileResource resource = new UploadFileResource();
        resource.setOriginalFileName(file.getOriginalFilename());
        resource.setNewFileName(newFileName.substring(newFileName.lastIndexOf(File.separator)+1));
        String url = newFileName.substring(newFileName.indexOf(Config.getBasePath())+Config.getBasePath().length()-1);
        if(File.separator.equals("\\")){
            url = url.replaceAll("\\\\","/");
        }
        resource.setUrl(url);
        return new RestResult(1L,resource);
    }

}
